package zzps.exeed.web.handle.argument;

import zzps.exeed.kernel.convert.Convert;
import zzps.exeed.kernel.holder.ModelAttribute;
import zzps.exeed.kernel.holder.ParameterHolder;
import zzps.exeed.kernel.tool.ReflectTool;
import zzps.exeed.kernel.tool.StrTool;
import zzps.exeed.web.Context;
import zzps.exeed.web.annotation.Model;

import java.lang.reflect.Field;
import java.util.List;

public class ModelMethodArgumentResolver implements HandlerMethodArgumentResolver{
    @Override
    public boolean support(ParameterHolder parameterHolder) {
        return parameterHolder.hasParameterAnnotation(Model.class);
    }

    @Override
    public Object resolveArgument(ParameterHolder parameterHolder, Context context) {
        Class<?> aClass = parameterHolder.getType();
        ModelAttribute modelAttribute = parameterHolder.getModelAttribute();
        if (modelAttribute != null){
            Object newInstance = ReflectTool.newInstance(modelAttribute.getConstructor());
            List<Field> fields = modelAttribute.getFields();
            for (Field field : fields) {
                String parameter = context.getParameter(field.getName());
                if (StrTool.isEmpty(parameter)){
                    continue;
                }
                Object convert = Convert.convert(field.getType(), parameter);
                ReflectTool.setField(newInstance,convert,field);
            }
            return newInstance;
        }
        return null;
    }
}
